﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace EzDesk.Core.ServiceImpl.Services
{
    class EzToken
    {
        // Token过期时间 todo: 从配置文件中读入
        public static readonly TimeSpan TokenExpireSpan = TimeSpan.FromHours(24);

        public string TokenString { get; set; }
        public DateTime ExpireOn { get; set; }
    }

    // todo: 线程并发安全性
    public class ClientTokenPool
    {
        private ClientTokenPool() { }
        public static readonly ClientTokenPool Instance = new ClientTokenPool();

        Dictionary<string, EzToken> tokenPool = new Dictionary<string, EzToken>();

        public string RequestToken(Guid userId)
        {
            string tokenString = null;
            if (tokenPool.ContainsKey(userId.ToString()) && tokenPool[userId.ToString()].ExpireOn > DateTime.Now)
            {
                tokenString = tokenPool[userId.ToString()].TokenString;
            }
            else
            {
                if (tokenPool.ContainsKey(userId.ToString()))
                {
                    tokenPool.Remove(userId.ToString());
                }

                tokenString = Guid.NewGuid().ToString();
                tokenPool.Add(userId.ToString(), new EzToken() { TokenString = tokenString, ExpireOn = DateTime.Now.Add(EzToken.TokenExpireSpan) });
            }
            return tokenString;
        }
        
        public void UpdateToken(Guid userId)
        {
            if (tokenPool.ContainsKey(userId.ToString()))
            {
                tokenPool[userId.ToString()].ExpireOn = DateTime.Now.Add(EzToken.TokenExpireSpan);
            }
            else
            {
                throw new Exception("没有合法的已注册UserId");
            }
        }

        public Guid GetUserIdByToken(string tokenString)
        {
            var item = tokenPool.First(p => p.Value.TokenString == tokenString);
            
            return new Guid(item.Key);
        }
    }
}
